
## libraries
if (!require("pacman")) install.packages("pacman")
pacman::p_load(reporttools, ggplot2, car,broom,stringr,interplot,TeachingDemos)

txtStart("repreport.txt")



### Load Data
load("data.RData")

## Recode variables to combine both party and ideology cues
alldata$partytype <- interaction(alldata$type,alldata$party_condition)
alldata$partytype <- as.factor(car::recode(as.numeric(alldata$partytype),"1:2='Control';3='In-Party Cue';4='Out-Party Cue'"))
alldata$ideologytype <- interaction(alldata$type,alldata$ideology_condition)
table(alldata$ideologytype)
alldata$ideologytype <- as.factor(car::recode(as.numeric(alldata$ideologytype),"1:2='Control';3='In-Party Extremist';4='Out-Party Extremist';5='In-Party Moderate';6='Out-Party Moderate'"))
alldata$con <- droplevels(interaction(alldata$ideologytype,alldata$partytype))

alldata$con <- factor(alldata$con,labels=c("Control","In-Party Extremist","In-Party Moderate","Out-Party Extremist","Out-Party Moderate","In-Party Cue","In-Party Extremist & In-Party Cue","In-Party Moderate & In-Party Cue","Out-Party Cue","Out-Party Extremist & Out-Party Cue","Out-Party Moderate & Out-Party Cue"))
alldata$con <- factor(alldata$con, levels=levels(alldata$con)[c(1,6,9,3,2,5,4,8,7,11,10)])
a <- (lm(ft~con,alldata))
summary(a)


forplot <- broom::tidy(a)
forplot$term <- str_remove(forplot$term,"con")
forplot$term <- factor(forplot$term,levels=rev(levels(alldata$con)))
ggplot(forplot[-1,],aes(x=term,y=estimate))+coord_flip()+geom_pointrange(aes(ymin=estimate-1.96*std.error,ymax=estimate+1.96*std.error))+theme_bw()+geom_hline(aes(yintercept=0),lty=2)+ylab("Effect")+xlab("")+theme(text =element_text(size=20))
ggsave("maineffects.pdf",width=10,height=10)


## Extremity plot
## Reclde distance from midpoint
alldata$extremity <- abs(alldata$ideology-.5)/.5

## Not sorted ideologues recoded as 0
alldata$extremity[alldata$ideology>.5 & alldata$party=='democrat']=0
alldata$extremity[alldata$ideology<.5 & alldata$party=='republican']=0


a <- (lm(ft~con*extremity,alldata))
summary(a)


forplot <- interplot(a,var1="con",var2="extremity",steps = 100)
forplot <- forplot$data
forplot$value <- stringr::str_remove(forplot$value,"con")
forplot$value <- factor(forplot$value,levels=levels(alldata$con)[-1])

ggplot(forplot,aes(x=fake,y=coef1))+geom_ribbon(aes(ymin=lb,ymax=ub),alpha=.2)+facet_wrap(~value,nrow = 5)+geom_line()+ylab("Effect")+xlab("Ideological Extremity")+theme_bw()
ggsave("ideologicalextremity.pdf",width=6,height=8)

## Appendix Demographics
alldata$income <- relevel(alldata$income,ref='Less than $10,000')
sink("sampledemos.tex")
tableNominal(with(alldata,data.frame(age,race,sex,income)),cap = "Sample Demographics")
sink()
txtStop()
